/*
 * SendMailSSL.java
 *
 * Created on Jul 20, 2011, 7:50:10 PM
 */
package security;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
import hirondelle.web4j.util.Util;

/**
 * 
 * @author Keith
 */
@SuppressWarnings("serial")
public class SendMailSSL extends JFrame {

	/** Creates new form SendMailSSL */
	public SendMailSSL() {
		initComponents();
	}
	
	private void initComponents() {

		jTextField1 = new JTextField();
		jTextField2 = new JTextField();
		jLabel1 = new JLabel();
		jLabel2 = new JLabel();
		jButton1 = new JButton();
		jLabel3 = new JLabel();
		jLabel4 = new JLabel();
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setTitle("Forgot Password");

		jLabel1.setText("Username:");

		jLabel2.setText("Email:");

		jButton1.setText("Submit");
		ButtonHandler handler = new ButtonHandler();
		jButton1.addActionListener(handler);

		jLabel3.setText("An email will be sent to the ");

		jLabel4.setText(" Email address provided.");

		GroupLayout layout = new GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addGap(99, 99, 99)
								.addGroup(
										layout.createParallelGroup(
												GroupLayout.Alignment.TRAILING)
												.addComponent(jLabel2)
												.addComponent(jLabel1))
								.addGap(18, 18, 18)
								.addGroup(
										layout.createParallelGroup(
												GroupLayout.Alignment.LEADING)
												.addComponent(
														jTextField2,
														GroupLayout.PREFERRED_SIZE,
														91,
														GroupLayout.PREFERRED_SIZE)
												.addComponent(jButton1)
												.addComponent(
														jTextField1,
														GroupLayout.PREFERRED_SIZE,
														91,
														GroupLayout.PREFERRED_SIZE))
								.addContainerGap(120, Short.MAX_VALUE))
				.addGroup(
						GroupLayout.Alignment.TRAILING,
						layout.createSequentialGroup()
								.addContainerGap(137, Short.MAX_VALUE)
								.addGroup(
										layout.createParallelGroup(
												GroupLayout.Alignment.LEADING)
												.addComponent(jLabel4)
												.addComponent(jLabel3))
								.addGap(112, 112, 112)));
		layout.setVerticalGroup(layout
				.createParallelGroup(GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addComponent(jLabel3)
								.addPreferredGap(
										LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(jLabel4)
								.addGap(51, 51, 51)
								.addGroup(
										layout.createParallelGroup(
												GroupLayout.Alignment.BASELINE)
												.addComponent(jLabel1)
												.addComponent(
														jTextField1,
														GroupLayout.PREFERRED_SIZE,
														GroupLayout.DEFAULT_SIZE,
														GroupLayout.PREFERRED_SIZE))
								.addGap(18, 18, 18)
								.addGroup(
										layout.createParallelGroup(
												GroupLayout.Alignment.LEADING)
												.addComponent(jLabel2)
												.addComponent(
														jTextField2,
														GroupLayout.PREFERRED_SIZE,
														GroupLayout.DEFAULT_SIZE,
														GroupLayout.PREFERRED_SIZE))
								.addGap(18, 18, 18).addComponent(jButton1)
								.addContainerGap(55, Short.MAX_VALUE)));
		pack();
	}
	
	public static void main(String args[]) {
		SendMailSSL window = new SendMailSSL();
		window.addWindowListener(new WindowAdapter() {

			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
	}

	public static void create() {
		new SendMailSSL().setVisible(true);
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	static JButton jButton1;
	static JLabel jLabel1;
	static JLabel jLabel2;
	static JLabel jLabel3;
	static JLabel jLabel4;
	static JTextField jTextField1;
	static JTextField jTextField2;
	// End of variables declaration//GEN-END:variables
	private static ResultSet res;
	private static Connection connect;
	private static String password2;
	private static String d_email = "noreplyjava@gmail.com",
			d_password = "mystic12!", d_host = "smtp.gmail.com",
			d_port = "465", m_to, m_subject = "Your Password", m_text;
	private static boolean valid;

	@SuppressWarnings("unused")
	public static void sendmail() throws SQLException {
		try {
			try {
				Class.forName("com.mysql.jdbc.Driver")
						.newInstance();
				// Get a connection
				connect = DriverManager.getConnection(JavaDB.dbUrl, "root" , "root");
			} catch (Exception except) {
				except.printStackTrace();
				System.exit(0);
			}

			Statement stmnt = connect.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			res = stmnt.executeQuery("select * from userTable where "
					+ "username= '" + jTextField1.getText() + "'");
			res.first();
			if (res.first() == false) {
				JOptionPane.showMessageDialog(null, "There is no user "
						+ "registered with that name.", "Error",
						JOptionPane.ERROR_MESSAGE);
				System.exit(0);
			}
			stmnt.close();
			password2 = res.getString("Password");
			m_text = "Your password is '" + password2 + "'";
			m_to = jTextField2.getText();
			String emailAddress = jTextField2.getText();
			valid = isValidEmailAddress(emailAddress);

			if (valid == false) {
				JOptionPane.showMessageDialog(null, "Not a valid email",
						"Error", JOptionPane.ERROR_MESSAGE);
				System.exit(0);
			}
			Properties props = new Properties();
			props.put("mail.smtp.user", d_email);
			props.put("mail.smtp.host", d_host);
			props.put("mail.smtp.port", d_port);
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.auth", "true");
			// props.put("mail.smtp.debug", "true");
			props.put("mail.smtp.socketFactory.port", d_port);
			props.put("mail.smtp.socketFactory.class",
					"javax.net.ssl.SSLSocketFactory");
			props.put("mail.smtp.socketFactory.fallback", "false");
			SecurityManager security = System.getSecurityManager();

			try {
				Authenticator auth = new SMTPAuthenticator();
				Session session = Session.getInstance(props, auth);
				// session.setDebug(true);

				MimeMessage msg = new MimeMessage(session);
				msg.setText(m_text);
				msg.setSubject(m_subject);
				msg.setFrom(new InternetAddress("noreply@mathofmattix.com"));
				msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
						m_to));
				Transport.send(msg);
				System.out.println("Done");
			} catch (Exception mex) {
				mex.printStackTrace();
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}

		JOptionPane.showMessageDialog(null, "Your password has been sent"
				+ "\nPlease allow up to 5 minutes for delivery.");
		System.exit(0);

	}

	@SuppressWarnings("unused")
	public static boolean isValidEmailAddress(String aEmailAddress) {
		if (aEmailAddress == null) {
			return false;
		}
		boolean result = true;
		try {
			InternetAddress emailAddr = new InternetAddress(aEmailAddress);
			if (!hasNameAndDomain(aEmailAddress)) {
				result = false;
			}
		} catch (AddressException ex) {
			result = false;
		}
		return result;
	}

	private static boolean hasNameAndDomain(String aEmailAddress) {
		String[] tokens = aEmailAddress.split("@");
		return tokens.length == 2 && Util.textHasContent(tokens[0])
				&& Util.textHasContent(tokens[1]);
	}

	private class ButtonHandler implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource().equals(jButton1)) {
				try {
					sendmail();
				} catch (SQLException ex) {
					ex.printStackTrace();
				}

			}
		}
	}

	private static class SMTPAuthenticator extends Authenticator {

		public PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(d_email, d_password);
		}
	}
}
